﻿using System;
using System.Data;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Single_SignOn.Attributes;
using Single_SignOn.Models;
using Single_SignOn.ResX;
using Single_SignOn.Json;
using Single_SignOn.Areas.Web.Models;
namespace Single_SignOn.Areas.Web.Controllers
{
    public class LoginController : Controller
    {
        private DataAccess.SingleSignOn.AuthenConnection oAuth;
        //
        // GET: /PC/oLogin/
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Index()
        {
            return View("Index");
        }

        
        public JsonResult GetCookies(string Username, string password, string Remember)
        {
            var record = this.ControllerContext.HttpContext.Request.Cookies[string.Format("{0}{1}"
                , WebConfig.Cookies, Username.ToLower())];
            var result = new object();
            if (record != null)
                if (!record.HasKeys)
                {
                    result = new
                    {
                        Name = record.Name.Replace(WebConfig.Cookies, ""),
                        Pass = record.Value,
                        Remember = true
                    };
                    return Json(result, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    result = new
                    {
                        Name = Username,
                        Pass = password,
                        Remember = Convert.ToBoolean(Remember)
                    };
                    return Json(result, JsonRequestBehavior.AllowGet);
                }

            result = new
            {
                Name = Username,
                Pass = password,
                Remember = Convert.ToBoolean(Remember)
            };
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [JsonFilterAttribute(Param = "oSubmitDataObj", RootType = typeof(oSubmitDataContract))]
        public JsonResult Submit(oSubmitDataContract oSubmitDataObj)
        {

            try
            {
                if (oSubmitDataObj.Remember)
                {
                    HttpCookie cookies = new HttpCookie(string.Format("{0}{1}"
                        , WebConfig.Cookies, oSubmitDataObj.Username.ToLower())
                        , oSubmitDataObj.Password);
                    cookies.Expires = DateTime.Now.AddDays(365);
                    this.ControllerContext.HttpContext.Response.Cookies.Add(cookies);
                }
                else
                {
                    HttpCookie cookie = new HttpCookie(string.Format("{0}{1}"
                        , WebConfig.Cookies, oSubmitDataObj.Username.ToLower())
                        , oSubmitDataObj.Password);

                    if (!string.IsNullOrEmpty(cookie.Name))
                        if (!cookie.HasKeys)
                        {
                            cookie.Expires = DateTime.Now.AddDays(-1);
                            this.ControllerContext.HttpContext.Response.Cookies.Add(cookie);
                        }
                }

                JsonResult js = new JsonResult();
                oAuth = new DataAccess.SingleSignOn.AuthenConnection();
                DataTable dt =
                    // Called Data Access

                    oAuth.getUserData(oSubmitDataObj.Username);
                if (dt != null)
                    if (dt.Rows.Count > 0)
                    {
                        // get Session
                        SessionPool.getSession(oSubmitDataObj.Username);
                        //*
                        UserProfile o = new UserProfile();
                        js = Json(new
                        {
                            redirectToUrl = Url.Action("Index"
                                , "ApplicationList"
                                , (UserProfile)o
                                , "http")
                             ,
                            exception = ""
                        });
                    }
                    else
                    {
                        js = Json(new
                        {
                            redirectToUrl = Url.Action("Index"
                                , "ApplicationList"
                                , ""
                                , "http")
                             ,
                            exception = ResourceTools.GetResource("Resource", "DataNotFound")
                        });
                    }

                else
                {
                    js = Json(new
                    {
                        redirectToUrl = Url.Action("Index"
                            , "ApplicationList"
                            , ""
                            , "http")
                                 ,
                        exception = ResourceTools.GetResource("Resource", "DataNotFound")
                    });
                }


                return js;
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }

        [AllowAnonymous]
        public ActionResult LogOut(String UserInfo)
        {
            Session.Remove("UserInfo");
            Session["UserInfo"] = null;
            return RedirectToAction("Index","Authentication");
        }

        public ActionResult Access(ButtonModels models)
        {
            return PartialView("_button", models);
            //return null;
        }

        /*
        public void getSession(string username)
        {
            oAuth = new DataAccess.SingleSignOn.AuthenConnection();

            DataTable dtUserData = oAuth.getUserData(username);
            UserProfile oUserProfile;//= new UserProfile();
            if (dtUserData != null)
                if (dtUserData.Rows.Count > 0)
                {
                    Session.Remove("UserInfo");
                    oUserProfile = new UserProfile();
                    oUserProfile.Description = (System.DBNull.Value == dtUserData.Rows[0]["DESCRIPTION"]) ? "" : (string)dtUserData.Rows[0]["DESCRIPTION"];
                    oUserProfile.GroupDescription = (System.DBNull.Value == dtUserData.Rows[0]["GROUPDESC"]) ? "" : (string)dtUserData.Rows[0]["GROUPDESC"];
                    oUserProfile.EmployeeNo = (System.DBNull.Value == dtUserData.Rows[0]["EMPID"]) ? "" : (string)dtUserData.Rows[0]["EMPID"];
                    oUserProfile.Username = (System.DBNull.Value == dtUserData.Rows[0]["EMPNO"]) ? "" : (string)dtUserData.Rows[0]["EMPNO"];
                    oUserProfile.FullName = (System.DBNull.Value == dtUserData.Rows[0]["EMPNAME"]) ? "" : (string)dtUserData.Rows[0]["EMPNAME"];
                    oUserProfile.Password = (System.DBNull.Value == dtUserData.Rows[0]["PASSWORD"]) ? "" : (string)dtUserData.Rows[0]["PASSWORD"];
                    oUserProfile.GroupNo = (System.DBNull.Value == dtUserData.Rows[0]["GROUPNO"]) ? "" : (string)dtUserData.Rows[0]["GROUPNO"];
                    oUserProfile.Division = (System.DBNull.Value == dtUserData.Rows[0]["DIVISION"]) ? "" : (string)dtUserData.Rows[0]["DIVISION"];
                    oUserProfile.Store = (System.DBNull.Value == dtUserData.Rows[0]["STORENO"]) ? "" : (string)dtUserData.Rows[0]["STORENO"];
                    oUserProfile.Tel = (System.DBNull.Value == dtUserData.Rows[0]["TEL"]) ? "" : (string)dtUserData.Rows[0]["TEL"];
                    oUserProfile.Email = (System.DBNull.Value == dtUserData.Rows[0]["EMAIL"]) ? "" : (string)dtUserData.Rows[0]["EMAIL"];
                    oUserProfile.Status = (System.DBNull.Value == dtUserData.Rows[0]["STATUS"]) ? "" : (string)dtUserData.Rows[0]["STATUS"];
                    oUserProfile.ApplNo = (System.DBNull.Value == dtUserData.Rows[0]["APPLNO"]) ? "" : (string)dtUserData.Rows[0]["APPLNO"];
                    oUserProfile.ProfileLevel = (System.DBNull.Value == dtUserData.Rows[0]["PROFILELEVEL"]) ? "" : (string)dtUserData.Rows[0]["PROFILELEVEL"];
                    oUserProfile.Language = (System.DBNull.Value == dtUserData.Rows[0]["LANG"]) ? "" : (string)dtUserData.Rows[0]["LANG"];
                    Session["UserInfo"] = oUserProfile;
                }
        }
        
         
        [HttpPost]
        [AcceptSubmitType(Name = "State", Type = "Login")]
        public void Login()
        {
        }

        [HttpPost]
        public ActionResult State(string state)
        {
            return Redirect("/");
        }

        [HttpPost]
        [MultipleButton(Name = "State", Argument = "Send")]
        public void Send()
        {
        }

        [HttpPost]
        [MultiButton(MatchFormKey = "State", MatchFormValue = "Send")]
        public void Action()
        {
        }

        public ActionResult Index(FormCollection collection, LoginModels models)
        {
            LoginModels model = new LoginModels();
            if (System.Web.HttpContext.Current.Request.Cookies[string.Format("{0}{1}"
                , WebConfig.Cookies, models.Username)] != null)
            {
                model.Username = models.Username;
                model.Password = (String)System.Web.HttpContext.Current.Request.Cookies[string.Format("{0}{1}"
                    , WebConfig.Cookies, models.Username)].Value;
                model.RememberMe = true;
            }
            else
            {
                model.Username = models.Username;
                model.Password = models.Password;
                model.RememberMe = models.RememberMe;
            }
            return View(model);
        }
        */
    }
}
